package com.itheima.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 事物管理类（开启，提交，回顾，释放）
 */
@Component("transactionManager")
public class TransactionManager {


    @Autowired
    @Qualifier("connectionUtils")
    private ConnectionUtils connectionUtils;

    /**
     * 开启事务
     * @throws SQLException
     * @return void
     */
    public void start() throws SQLException {
        connectionUtils.getThreadConnection().setAutoCommit(false);
    }

    /**
     * 提交事务
     * @throws SQLException
     * @return void
     */
    public void commit() throws SQLException {
        connectionUtils.getThreadConnection().commit();
    }

    /**
     * 回滚事务
     * @throws SQLException
     * @return void
     */
    public void rollback() throws SQLException {
        connectionUtils.getThreadConnection().rollback();
    }

    /**
     * 释放事务
     * @throws SQLException
     * @return void
     */
    public void release() throws SQLException {
        connectionUtils.getThreadConnection().close();
        connectionUtils.removeConnection();
    }
}
